package com.ks.community.controller;


import com.atguigu.commonutils.R;
import com.atguigu.vo.IngredientVo;
import com.atguigu.vo.MenuSearchVo;
import com.ks.community.entity.Ingredient;
import com.ks.community.entity.vo.MenuIngredientVo;
import com.ks.community.entity.vo.MenuVo;
import com.ks.community.feign.SearchFeign;
import com.ks.community.service.MenuIngredientService;
import com.ks.community.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dCoder
 * @since 2022-03-29
 */
@RestController
@RequestMapping("/community/menu")
public class MenuController {

    @Autowired
    MenuService menuService;
    @Autowired
    MenuIngredientService menuIngredientService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    SearchFeign searchFeign;

    //发布菜谱
    @PostMapping("add")
    public R addMenu(@RequestBody MenuVo menuVo){
        String userId = stringRedisTemplate.opsForValue().get("userId");
        if(userId == null){
            return R.error().message("请先登录");
        }
        menuVo.setUserId(userId);
        String menuId = menuService.saveOne(menuVo);

        MenuSearchVo menuSearchVo = new MenuSearchVo();
        menuSearchVo.setMenuId(menuId);
        menuSearchVo.setMenuStep(menuVo.getMenuStep());
        menuSearchVo.setMenuName(menuVo.getMenuName());
        menuSearchVo.setMenuImg(menuVo.getMenuImg());
        menuSearchVo.setLikedNumber(0);
        menuSearchVo.setCollectedNumber(0);
        menuSearchVo.setUserId(menuVo.getUserId());
        menuSearchVo.setCostTime(menuVo.getCostTime());
        menuSearchVo.setFlavor("清淡");

        List<Ingredient> ingredients = menuVo.getIngredients();
        List<IngredientVo> ingredientVos = new ArrayList<>();
        for (Ingredient ingredient:ingredients){
            IngredientVo ingredientVo = new IngredientVo();
            BeanUtils.copyProperties(ingredient,ingredientVo);
            ingredientVos.add(ingredientVo);
        }
        menuSearchVo.setIngredients(ingredientVos);
        searchFeign.addMenuVo(menuSearchVo);
        return R.ok();
    }
    @PostMapping("/addIngredientByName")
    public R addIngredientByName (@RequestBody MenuIngredientVo menuIngredientVo){
        String gredName =  menuIngredientVo.getIngredientName();
        String MenuName =  menuIngredientVo.getMenuName();
        menuIngredientService.addIngredientByName(menuIngredientVo);
        return R.ok();
    }



}

